package com.gongguizhijia.Util;

/**
 * @description:
 * @author：chj
 * @time：2021/6/7 11:48
 */

import java.io.File;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CountColumnUtil {

    /**
     * 获取表格全部 字段属性
     *
     * @param ExcelName
     * @throws Exception
     */
    public static Set<String> getColumnName(String ExcelName) throws Exception {
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        String desktopPath = "D:/jjf";
        List<String> fileList = getFileName();
        String mdbPath = null;
        Set<String> set = new HashSet<>();
        for (String fileName : fileList) {
            mdbPath = fileName;

            Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + desktopPath + "//" + mdbPath);

            DatabaseMetaData metaData1 = conn.getMetaData();
            ResultSet tables = metaData1.getTables(null, null, "%", null);
            while (tables.next()) {
                String tablesString = tables.getString(3);
                if (ExcelName.equals(tablesString)) {
                    Statement stmt = conn.createStatement();
                    String sql = "SELECT * FROM " + ExcelName;
                    ResultSet rs = stmt.executeQuery(sql);
                    ResultSetMetaData metaData = rs.getMetaData();
                    int count = metaData.getColumnCount();

                    while (rs.next()) {
                        for (int i = 1; i <= count; i++) {
                            String columnName = metaData.getColumnName(i);
                            set.add(columnName);
                        }
                    }
                    rs.close();
                    stmt.close();
                    conn.close();
                }
            }
        }
        return set;
    }

    /**
     * 获取文件夹下所有文件名称
     */
    public static List<String> getFileName() {
        List<String> fileNameList = new ArrayList<>();
        /** 路径 */
        String path = "D:/jjf";
        File f = new File(path);
        if (!f.exists()) {
            System.out.println(path + " not exists");
            return null;
        }

        File[] fa = f.listFiles();
        for (int i = 0; i < fa.length; i++) {
            File fs = fa[i];
            if (fs.isDirectory()) {
                System.out.println(fs.getName() + " [目录]");
            } else {
                fileNameList.add(fs.getName());
            }
        }
        return fileNameList;
    }

}